#include <QJsonParseError>
#include <QJsonObject>
#include <QSettings>
#include "settings.h"
#include "config.h"
#include "loginservice.h"

LoginService::LoginService(QObject *parent) : QObject(parent)
{
    _username = "";
    _password = "";
    _nam = new QNetworkAccessManager(this);
    connect(_nam, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(slot_login_res(QNetworkReply*)));
}

QString LoginService::username(){
    return _username;
}

void LoginService::setUsername(QString str){
    _username = str;
}

QString LoginService::password(){
    return _password;
}

void LoginService::setPassword(QString str){
    _password = str;
}

void LoginService::slot_login_res(QNetworkReply * reply)
{
	//    int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
	//    qDebug()<<status;

	if (reply->error() == QNetworkReply::NoError) {
		QByteArray data = reply->readAll();
		qDebug() << data;
		QJsonParseError jsonpe;
		QJsonDocument json = QJsonDocument::fromJson(data, &jsonpe);
		if (jsonpe.error == QJsonParseError::NoError)
		{
			if (json.isObject()) {
				QJsonObject obj = json.object();
				int code = obj["status"].toInt();
				QString msg = obj["msg"].toString();
				if (code == 1) {
					Settings settings;
					QJsonObject data = obj["data"].toObject();
					settings.beginGroup("user");
					foreach(QString uk, data.keys()) {
						if (data.value(uk).isString()) {
							settings.setValue(uk, data.value(uk).toString());
						}
						else if (data.value(uk).isDouble()) {
							settings.setValue(uk, data.value(uk).toDouble());
						}

					}
					settings.endGroup();
				}

				emit sig_login_result(code, msg);
			}
		};
	}
	else {
		qDebug() << reply->error();
	}
	reply->deleteLater();
}

void LoginService::slot_login_req(){
    QString url = API_URL+"default/login";
    QUrl qurl(url);
    QNetworkRequest req(qurl);
    req.setRawHeader("content-type","application/x-www-form-urlencoded");

    QByteArray data;
    data.append("username="+_username+"&");
    data.append("password="+_password+"&");
    data.append("phone_type="+1);
    _nam->post(req,data);
}
